import Dexie from 'dexie';
var dbData = {
  friends: "++id,name,age",
  jj: "++id,name,kind"
}

class DB {
  constructor() {
    var versionCode = Dexie.version;
    var dbName = "database";
    var dexie = null;
    this.init = function (userId,callfun) {
      if (checkDB()) {
        this.destroy();
      }
      dbName = "database_"+ userId;
      dexie = new Dexie(dbName);
      dexie.version(versionCode).stores(dbData)
      dexie.open().then(function (db) {
        versionCode = db.verno;
        if(callfun) {callfun(true)};
      }).catch(function () {
        dexie.close();
        dexie = new Dexie(dbName);
        dexie.open().then(function (db) {
          versionCode = db.verno;
          if(callfun) {callfun(true)};
        }).catch(function () {
          if(callfun) {callfun(false)};
        })
      })
    }

    this.createTable = function (params,callfun) {
      function storeTable (data) {
        dexie.close();
        versionCode = (versionCode * 10 + 1)/10;
        dexie.version(versionCode).stores(data);
        dexie.open().then(function (db) {
          versionCode = db.verno;
          if(callfun) {callfun(true)};
        }).catch(function () {
          if(callfun) {callfun(false)};
        });
      }
      dexie.open().then(function (db) {
        versionCode = db.verno;
        storeTable(params);
      }).catch(function () {
        if(callfun) {callfun(false)};
      });
    }

    function checkDB () {
      if (dexie != null && !dexie.isOpen())
      {
        return true;
      }
      return false;
    }

    this.destroy = function () {
      if (!checkDB()) return;
      dexie.delete().then(function () {

      }).catch(function (e) {
        console.log(e);
      });
      dexie = null;
    }
  }
}

export default (function () {
  var instantiated;
  return {
    getInstance: () => {
      if (!instantiated)
      {
        instantiated = new DB();
      }
      return instantiated;
    },
  }
})()
